#include "link.h"

int Link::count=0;

Link::Link():QObject(){
    _progress=0;
    _speed=0;
    changed=true;
    _state=FREE;
    _client=NULL;
    _proxy=NULL;
    _index=count++;
};

QString Link::fileDownloadName(){
    setState(Link::DOWNLOADING_FILE);
    QString path=url().path();
    QString file=path.right(path.length()-path.lastIndexOf("/")-1);
    speedTimer=QTime::currentTime();
    speedCounter=0;
    if(file.endsWith(".html"))
        return file.left(file.length()-5);
    return file;
};

void Link::downloadProgress(qint64 prog,qint64 tot){
    changed=TRUE;
    _progress=prog*10000/tot;
    int sP=speedTimer.secsTo(QTime::currentTime());
    if(sP>5){
        _speed=(prog-speedCounter)/sP;
        speedCounter=prog;
        speedTimer=QTime::currentTime();
    }

};

QDomElement Link::xmlDesc(QDomDocument* doc){
    changed=FALSE;
    QDomElement mainTag=doc->createElement("link");
    (mainTag.appendChild(doc->createElement("index")).appendChild(doc->createTextNode(QString().number(_index))));
    (mainTag.appendChild(doc->createElement("url")).appendChild(doc->createTextNode(_url.toString())));
    if(_proxy!=NULL){
        (mainTag.appendChild(doc->createElement("proxy")).appendChild(doc->createTextNode(QString().number(_proxy->index()))));
    }
    (mainTag.appendChild(doc->createElement("state")).appendChild(doc->createTextNode(QString().number(_state))));
    (mainTag.appendChild(doc->createElement("progress")).appendChild(doc->createTextNode(QString().number(_progress))));
    (mainTag.appendChild(doc->createElement("speed")).appendChild(doc->createTextNode(QString().number(_speed))));
    return mainTag;
}

int Link::state(){
    return _state;
};
void Link::setState(int a){
    changed=TRUE;
    if((a==FINISHED)&&(_progress!=10000)){
        _state=ERR_SOCKET_ERROR;
    }else{
        _state=a;
    }
};

HttpClient* Link::client(){
    return _client;
};
void Link::setClient(HttpClient* a){
    changed=TRUE;
    _client=a;
};
QUrl Link::url(){
    return _url;
};
QString Link::hostService(){
    return _url.host();
}
void Link::setUrl(QUrl a){
    changed=TRUE;
    _url=a;
};

ProxyDesc* Link::proxy(){
    return _proxy;
};
void Link::setProxy(ProxyDesc* a){
    changed=TRUE;
    _proxy=a;
};
int Link::progress(){
    return progress();
};
